package standalone;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import corpus.SentPolarityCorpus;

public class GenerateTestSet {

	private Random r;
	private BufferedWriter out;
	private ArrayList<TreeMap<String, String>> entries;

	public static void main(String[] args) throws IOException {
		GenerateTestSet gen = new GenerateTestSet(new File(
				"corpus/polsent/test.txt"));
		ArrayList<Map.Entry<String, String>> entries = gen.generate(1000);
		gen.write(entries);
		SentPolarityCorpus newSet = new SentPolarityCorpus(
				"corpus/polsent/test.txt");

		for (String f : new File("corpus/polsentorig").list()) {
			if (f.contains("test.txt"))
				continue;
			SentPolarityCorpus spc = new SentPolarityCorpus(
					"corpus/polsentorig/" + f);
			spc.remove(newSet);
			spc.output(new BufferedWriter(new FileWriter("corpus/polsent/" + f)));
		}

	}

	public GenerateTestSet(File out) throws IOException {
		this.out = new BufferedWriter(new FileWriter(out));
		r = new Random();
		File dir = new File("corpus/polsentorig");
		entries = new ArrayList<TreeMap<String, String>>();
		for (String f : dir.list()) {
			if (f.contains("test.txt"))
				continue;
			SentPolarityCorpus spc = new SentPolarityCorpus(dir.getPath() + "/"
					+ f);
			for (String emo : new String[] { "neu", "pos", "neg" }) {
				TreeMap<String, String> emoMap = new TreeMap<String, String>();
				for (String sent : spc.getSentences(emo))
					emoMap.put(sent, emo);
				entries.add(emoMap);
			}
		}
	}

	private Map.Entry<String, String> pick(Map<String, String> set) {
		if (set.size() <= 1)
			throw new Error("Failed, empty map");
		int size = set.size();
		int target = r.nextInt(size);
		int index = -1;
		for (Map.Entry<String, String> s : set.entrySet()) {
			if (target != index + 1) {
				index++;
				continue;
			}
			set.remove(s);
			return s;
		}
		throw new Error("Failed, empty map");
	}

	public ArrayList<Map.Entry<String, String>> generate(int nbr) {
		int seti = -1;
		ArrayList<Map.Entry<String, String>> generated = new ArrayList<Map.Entry<String, String>>();
		for (int i = 0; i < nbr; i++) {
			seti = (seti + 1) % entries.size();
			Map.Entry<String, String> e = pick(entries.get(seti));
			generated.add(e);
		}
		return generated;
	}

	public void write(ArrayList<Map.Entry<String, String>> generated)
			throws IOException {
		for (Map.Entry<String, String> e : generated)
			out.append(e.getValue() + "\t" + e.getKey() + "\n");
		out.flush();
		out.close();
	}
}
